package com.example.mediaservice.websocket;

import org.springframework.stereotype.Controller;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CopyOnWriteArraySet;

@Controller
@ServerEndpoint("/websocket/image")
public class ReceiveWebsocketImage {
    public static final CopyOnWriteArraySet<ReceiveWebsocketImage> receImgSessions = new CopyOnWriteArraySet<>();
    public Session session;

    @OnOpen
    public void onOpen(Session session) throws IOException {
        System.out.println("onOpen");
        this.session = session;
        receImgSessions.add(this);
    }

    @OnClose
    public void onClose() throws IOException {
        System.out.println("onClose");
        receImgSessions.remove(this);
        this.session.close();
    }

    @OnMessage(maxMessageSize=1024*1024*3)
    public void onMessage(byte[] imgData, Session session) throws IOException {
        Object[] arr = SendImage.sendImgSessions.toArray();
        ByteBuffer byteBuffer=ByteBuffer.allocate(imgData.length);
        byteBuffer.put(imgData);
        byteBuffer.flip();
        for(Object _item:arr) {
            SendImage item = (SendImage) _item;
            item.sendMessage(byteBuffer);
            System.out.println("sendMessage => end : " + arr.length + " , " + byteBuffer.capacity());
        }
    }

    @OnError
    public void onError(Session session, Throwable error) throws IOException {
        System.out.println("onError");
        error.printStackTrace();
        receImgSessions.remove(this);
        session.close();
    }
}
